/**
 * @file Define the I18N service class in this module
 * 
 * @author Steve Gao<gaofu@parllay.com>
 */
const path          = require('path');
const fs            = require('fs');
const LRU           = require('lru-cache');

const BaseService   = require('./base-service').BaseService;

/**
 * I18N Service 
 * 
 * @class I18NService
 */
class I18NService extends BaseService {

    get localesPath() {
        return path.resolve(this.Context.getCurrentWorkDirectory(), 'static/locales');
    }

    constructor(context) {
        super(context);

        this.initializeI18N();
    }

    initializeI18N() {
        this.setupI18NCache();
    }

    setupI18NCache() {
        this._cache = new LRU({
            max: 500,
            maxAge: 1000 * 60 * 60
        });
    }

    getResourcesByLanguage(language, namespace) {
        namespace = namespace || 'resources';
        language = language || 'en';

        let resourcesFilePath = `${language}/${namespace}.json`;
        let resourcesJSON = this._cache.get(resourcesFilePath);
        let realResourcesFilePath = path.resolve(this.localesPath, resourcesFilePath);

        if (!resourcesJSON && fs.existsSync(realResourcesFilePath)) {
            let resourcesContent = fs.readFileSync(realResourcesFilePath);
            resourcesJSON = JSON.parse(resourcesContent);
            this._cache.set(resourcesFilePath, resourcesJSON);
        }

        return resourcesJSON;
    }
}

exports.I18NService = I18NService;